<template>
  <div>
    <audio ref="audioRef" src="./data/signin.mp3" preload="auto" muted></audio>
    <component
      v-if="store.courseReady ? store.courseWatchData : store.courseData"
      :is="store.courseReady ? CourseDetail : CourseCountdown"
    />
    <Signin
      v-if="
        store.courseWatchData &&
        signinStore?.isVisible &&
        store.courseData?.sign.openSignIn == 1
      "
      class="z-30"
    ></Signin>
    <!-- <RedPacket
      v-if="
        store.courseWatchData &&
        redPacketStore?.isVisible &&
        store.courseData?.redPacket.openRedPacket !== 0
      "
      class="z-10"
    ></RedPacket> -->
    <Question
      v-if="
        store.courseWatchData &&
        questionStore?.isVisible &&
        store.courseData?.questionNum > 0 &&
        store.courseData.screenType == 0
      "
      class="fixed top-0 left-0 w-full h-full z-20"
    ></Question>
    <WeatherCover :imgSrc="store.courseData?.transitionImg" />
  </div>
</template>

<script setup lang="ts">
import CourseCountdown from "./CourseCountdown.vue";
import CourseDetail from "./CourseDetail.vue";
import Signin from "./Signin.vue";
import RedPacket from "./RedPacket.vue";
import Question from "./Question.vue";
import { useTencentIM } from "@/utils/tencent-im";
import {
  useCourseData,
  useCourseSignin,
  useRedPacket,
  useQuestion
} from "../../store/useCourse";
import { onBeforeMount, onUnmounted, watch } from "vue";
import { useLocationParams } from "@/store/useLocationStore";
import { useQuestionnaireStore } from "@/store/useQuestionnaireStore";
import { isWeChatBrowserPro } from "@/utils/wechat";
import { ref } from "vue";
import router from "@/router";
import { usePlayerStore } from "@/store/usePlayer";
import WeatherCover from "@/components/WeatherCover.vue";
import { useUserStore } from "@/store/useUserStore";

const playerStore = usePlayerStore();
const store = useCourseData();
const { getParam, setParam } = useLocationParams();
const userStore = useUserStore();
if (!store.shareUserId) {
  store.setShareUserId(getParam("shareUserId"));
}
setParam("shareUserId", userStore.user.buyerUserId.toString());
let signinStore, redPacketStore, questionStore;
const props = defineProps<{
  roomId: string;
}>();
const { getAllParams } = useLocationParams();
const allParams = getAllParams();

// 音频播放相关
let audioTimer = null;
const hasUserInteracted = ref(false);
const audioRef = ref<HTMLAudioElement | null>(null);

// 音频播放函数
const playAudio = (options: { mute?: boolean } = {}) => {
  if (audioRef.value) {
    if (options.mute) {
      audioRef.value.muted = true;
    } else {
      audioRef.value.muted = false;
    }
    audioRef.value.play().catch(error => {
      console.error("Error playing audio:", error);
    });
  }
};

// 处理用户首次交互
const handleFirstInteraction = () => {
  if (!hasUserInteracted.value) {
    hasUserInteracted.value = true;
    // 只解除自动播放限制，不立即播放声音
    playAudio({ mute: true });
    // 移除事件监听器
    document.removeEventListener("click", handleFirstInteraction);
    document.removeEventListener("touchstart", handleFirstInteraction);
  }
};

onBeforeMount(async () => {
  const { getAllParams } = useLocationParams();
  const allParams = getAllParams();
  // useCourseSignin();
  if (isWeChatBrowserPro()) {
    const checkInviteCodeData = await store.checkInviteCode(
      allParams["inviteCode"]
    );
    if (!checkInviteCodeData) {
      return;
    } else {
      console.log("checkInviteCodeData", checkInviteCodeData);
      if (checkInviteCodeData?.adjustmentParam) {
        const rediData =
          await useQuestionnaireStore().checkRoomWatchRecordResult(
            checkInviteCodeData?.adjustmentParam
          );
        if (rediData) {
          router.push(rediData);
          return;
        }
      }
      const { errMsg } = checkInviteCodeData;
      if (errMsg) {
        router.push({
          path: "/course-error",
          query: {
            ...checkInviteCodeData
          }
        });
        return;
      }
    }
  }
  const data = await store.entryRoom(props.roomId);
  if (data) {
    document.title = data.shareVipTitle || data.title || data.shopName;
  }
  store.courseData?.userSig &&
    useTencentIM().loginChat({
      userSig: store.courseData.userSig,
      groupID: store.courseData.screeningId.toString()
    });

  // 添加用户交互监听
  document.addEventListener("click", handleFirstInteraction);
  document.addEventListener("touchstart", handleFirstInteraction);
});

watch(
  () => store.courseWatchData,
  () => {
    // 防止多次触发
    if (signinStore) {
      return;
    }
    signinStore = useCourseSignin();
    redPacketStore = useRedPacket();
    questionStore = useQuestion();
    // 处理刷新情况
    if (store.courseWatchData.answerState == 1) {
      if (questionStore.isCompleted) {
        return;
      }
      questionStore.setIsCompleted(true);
    }
    // 监听答题失败状态
    watch(
      () => questionStore.isFailed,
      async isFailed => {
        if (isFailed) {
          await store.answer(2);
          await store.watchCourse();
        }
      }
    );
    // 监听答题显示状态
    watch(
      () => questionStore.isVisible,
      isVisible => {
        if (isVisible) {
          playerStore.setFullScreen(false);
        }
      }
    );
    // 监听答题成功状态
    watch(
      () => questionStore.isCompleted,
      async isCompleted => {
        if (isCompleted) {
          await store.answer(1);
          await store.watchCourse();
        }
      }
    );

    // 监听签到弹窗显示状态
    watch(
      () => signinStore?.isVisible,
      isVisible => {
        if (isVisible) {
          playerStore.setFullScreen(false);
        }
        if (isVisible && store.courseData?.signInSound == 1) {
          playAudio();
          audioTimer && clearInterval(audioTimer);
          audioTimer = setInterval(playAudio, 5000);
        } else {
          if (audioRef.value) {
            audioRef.value.pause();
            audioRef.value.load();
          }
          if (audioTimer) {
            clearInterval(audioTimer);
            audioTimer = null;
          }
        }
      }
    );

    // 签到红包
    // watch(
    //   [() => signinStore?.isCompleted, () => redPacketStore?.isCompleted],
    //   ([isCompleted, isRedPacketCompleted]) => {
    //     if (store.courseData?.signInRedPacket == 1) {
    //       if (isCompleted && isRedPacketCompleted) {
    //         // redPacketStore.setIsVisible(true);
    //         store.reward(3);
    //       }
    //     }
    //   }
    // );
    // watch(signinStore?.isCompleted, () => {
    //   // 签到关联红包
    //   if (store.courseData?.signInRedPacket == 1) {
    //     if (signinStore.isCompleted) {
    //       redPacketStore.setIsVisible(true);
    //     }
    //   }
    // });
    // 答题红包 处理1/4情况
    // watch(
    //   () => questionStore.isCompleted,
    //   isCompleted => {
    //     if (!isCompleted && questionStore.isCompleted) {
    //       return;
    //     }
    //     if (
    //       store.courseData?.redPacket.openRedPacket == 1 ||
    //       store.courseData?.redPacket.openRedPacket == 3
    //     ) {
    //       store.reward(2);
    //       redPacketStore.setIsVisible(true);
    //     }
    //   }
    // );

    // 处理需要签到的答题红包
    watch(
      [() => questionStore?.isCompleted, () => signinStore?.isCompleted],
      ([isQuestionCompleted, isSigninCompleted]) => {
        if (store.courseWatchData.answerRewardState !== 0) {
          return;
        }
        if (
          store.courseData?.redPacket.openRedPacket == 1 ||
          store.courseData?.redPacket.openRedPacket == 3
        ) {
          if (isQuestionCompleted) {
            if (store.courseData?.signInRedPacket == 1) {
              if (isSigninCompleted) {
                store.reward(1);
              }
            } else {
              store.reward(1);
            }
          }
        }
      }
    );

    // 处理需要签到的时长红包
    watch(
      [() => redPacketStore?.isCompleted, () => signinStore?.isCompleted],
      ([isRedPacketCompleted, isSigninCompleted]) => {
        if (store.courseWatchData.completedRewardState !== 0) {
          return;
        }
        if (
          store.courseData?.redPacket.openRedPacket == 2 ||
          store.courseData?.redPacket.openRedPacket == 3
        ) {
          if (isRedPacketCompleted) {
            if (store.courseData?.signInRedPacket == 1) {
              if (isSigninCompleted) {
                store.reward(2);
              }
            } else {
              store.reward(2);
            }
          }
        }
      }
    );
    // 答题且完播红包 处理组合情况
    watch(
      [
        () => questionStore?.isCompleted,
        () => redPacketStore?.isCompleted,
        () => signinStore?.isCompleted
      ],
      ([isQuestionCompleted, isRedPacketCompleted, isSigninCompleted]) => {
        if (store.courseWatchData.combineRewardState !== 0) {
          return;
        }
        if (store.courseData?.redPacket.openRedPacket == 4) {
          // 组合红包
          if (isQuestionCompleted && isRedPacketCompleted) {
            if (store.courseData?.signInRedPacket == 1) {
              // 需要签到
              if (isSigninCompleted) {
                store.reward(3);
              }
            } else {
              // 不需要签到
              store.reward(3);
            }
          }
        }
      }
    );
  },
  { once: true }
);

onUnmounted(() => {
  store.endOnlineUpdater();
  store.stopTimer();
  store.resetTimer();
  // 清理音频相关
  if (audioTimer) {
    audioRef.value?.pause();
    audioRef.value.load();
    clearInterval(audioTimer);
  }
  document.removeEventListener("click", handleFirstInteraction);
  document.removeEventListener("touchstart", handleFirstInteraction);
});
</script>

<style scoped></style>
